package com.ocom.webapi.po;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Slf4j
public class RSADemo2 {

    public static final String KEY_ALGORITHM = "RSA";

    private static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALyRtnHHITve8tvQ4gemW+/IcRuS/uE+zCGL3SIhSgdEI3HeBgDz4MWKcheLEUqz4Yarg+P2gbOwxD9Embj7KmUCAwEAAQ==";

    private static final String PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvJG2ccchO97y29DiB6Zb78hxG5L+4T7MIYvdIiFKB0Qjcd4GAPPgxYpyF4sRSrPhhquD4/aBs7DEP0SZuPsqZQIDAQABAkAqjtxVS3Llt0iqcbdBsLsZH+zfI0rg/TJG8/EBje/OOZ9mTB9m1Bbl9O+nQTdHEVthjcbmBreYSOEdXRSx3OoBAiEA/kFiZAdisxq/amtvyD+6jh/NBehX9EbOu7TnO8zA/YECIQC93PJEB2M2qpsGWoUPv8KtXpNwBNVxLc4WfIPbxNdm5QIhAL6jYdWkoAGw9YMiqT7ZYdS8zWo3ivMywEGH47U30iCBAiBjxiBqL5eruqwNArS6OgOMKA9C5sdj2rZaisSgUSkBIQIhAMdBZtPFgELP7z4hykzfG7ACTrUM8AWTWnYMqCgDQ1P0";

    private static final String PRIVATE_KEY2 = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEArDel1UvvJ1GT0RfV9IVvSFCrEf3MX+Zr2O6en7Cu//K9PD9qzmsoBlEFLhSVYbrjJkDxrmsrawoISBrrHlKVPwIDAQABAkAxwH3LCf3UGRAgBsfLtUS52nw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extIPW9PtIXVaKBDgtwCRrikiKa4KlJ+cKZpG5lygCZooYFF8KnK1fKMcsNcP5L42s0T9qOJ+s8btuP5rxBWOxZ2S8KgF0pjhg+KcLLqdiGfzLk9KZqj2k9X7UpDGJjMo3dKzU380WybZbf8GmUy0fNiQxC1DoGSgKj2khU+hCOqyC8DYU9ucyRuYFK6R8lNMe+M+2u1OI+139ht0XHlB5";

    private static final String PUBLIC_KEY4 = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA6bG7mDQ4Qr5hj6KfMzWk9bqMMMvVXSq9x+5muaxZ2keHYmb+hSWKcgJHMFMTFHf/MPNYJw84oRp5yXVtGy9cARjQlm+H/AOhdAEuE4A7cmyOcCHnKByN4AwudJXYAeXosMwQwWYRb9K8+xrxvr3noz3b3Wdjoi5G6skN9pLcjKp1cITRnLztJ1XKruRpSdZLoXXpPlE9OcI7uef6f7PX4MpfNQn7X9Q72e+Z9xuNGdZWAIafO+gi4/T1/feM23GS7Ji/NNxHq7XYUrEbrpFsgws1D4It4YDsQC6KPs07D12n6R7ZDC9RkK3ft+GTqpTgJyBfgZ3YZsCCcBdD2oyiCPiV+wBvMPAvFwp5wqnuEt16GLPm9nocC/qM6p2GUfKzK3EbpetU5aqNXAg2nlOiWkdiDchVNvNNi63f+cTydYywZhP+GqBGExt03A0+ccTUzcq46DiaHjbIxCSbSZI3WidZ/j2RP1F0AfMpyxJW7Q2T3d7Au2WdUePs7CpHXH9yy1s8KITOYRlmE4X72tE9p6ja5KlR/SBkwEvHQMKvRCjO4DB59j045sAryG00zy2gEPPo4Gu1+eFiUuq6+DvdhWgTNMyAkTt7/h4YEdbP8IUnNumEWuTRLsLz5dL/kHH+KPR3gR57isBbMNZTFL1Vu+7dXvZfuvHT37dwTAeorlkCAwEAAQ==";
    private static final String PRIVATE_KEY5 = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEArukxAa-sc_PkaHaVQJYB2wU60vwoE32hlkTNeg5OBBEiMxNWsBKvLVE2l512RPje7t0yfHk74XArtBbcwUzrbQIDAQABAkBNCvQGHR4l-OC7zrfROgHZOkV914nDhAvfx7CGObTNfw80ISkGnv7a6Ci7ULuXvJyRwAJZ6DZp4Lv9bJ9npnMVAiEA6W27gNl3twfXPS9Czlgj_NrFG18yV_awhuLq80TQFV8CIQC_0urMd2wR2zjwCd4aIp_mxD9_-3UOPEp6QcQwv8pGswIhAMsSUYq4pbMvOQrbcKz-dOBmmg9D9BIeZFgUVP2pobTVAiB_goipmciwpfTXOvf0j4eTMmizfkd1SwaG9iif7x1amQIhAKLNFIf1qHTBooeuqWeGHuHXDNFq1NCNVS2Yea95CL-u";



    // 获取公钥
    public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    // 获取私钥
    public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {
        byte[] privateKeyByte = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }


    /**
     * 公钥加密
     *
     * @param text         待加密的明文字符串
     * @param publicKeyStr 公钥
     * @return 加密后的密文
     */
    public static String encrypt(String text, String publicKeyStr) {
        try {
            log.info("明文字符串为:[{}]", text);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));
            byte[] tempBytes = cipher.doFinal(text.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(tempBytes);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param secretText    待解密的密文字符串
     * @param privateKeyStr 私钥
     * @return 解密后的明文
     */
    public static String decrypt(String secretText, String privateKeyStr) {
        try {
            // 生成私钥
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyStr));
            // 密文解码
            byte[] secretTextDecoded = Base64.getDecoder().decode(secretText.getBytes("UTF-8"));
            byte[] tempBytes = cipher.doFinal(secretTextDecoded);
            return new String(tempBytes);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + secretText + "]时遇到异常", e);
        }
    }

    public static void main(String[] args) throws Exception {
        String cipherText;
        // 原始明文
        String code = "userkey=111";

        log.info("公钥:[{}]，长度:[{}]", PUBLIC_KEY, PUBLIC_KEY.length());
        log.info("私钥:[{}]，长度:[{}]", PRIVATE_KEY, PRIVATE_KEY.length());

        // 加密用户标识
        cipherText = encrypt(code, PUBLIC_KEY);

        log.info("加密后的密文:{}，长度:{}]", cipherText, cipherText.length());
        String url = "https://home.firefoxchina.cn?"+cipherText;
        String encode = URLEncoder.encode(url, "UTF-8");
        log.info("传过去的url:{}", encode);
        // 解密
        String decode = URLDecoder.decode(encode, "UTF-8");
        log.info("接收后处理url:{}", decode);
        String text = decode.split("\\?")[1];
        String plainText = decrypt(text, PRIVATE_KEY);
        log.info("解密后明文:{}", plainText);





        //最新 2023年5月26日15:38:08
        String ocomcode = "http%3A%2F%2Fhnjh.ocomtraffic.com%2Fm%2F%23mine%3Fcode%3DKR52m5QgWcroDR0NEaOG3qqiJA1S7VmrRMWZPLScNHm%2BpMSS0OprC0qtHFVDKFonvqkAbcSYOHGbwMytv9uqEg%3D%3D";
        String ocomcodeUrlDecode =   URLDecoder.decode(ocomcode, "UTF-8");
        log.info("接收后处理url:{}", ocomcodeUrlDecode);
        String text2 = ocomcodeUrlDecode.split("\\?")[1];
        System.out.println(text2.substring(5));
        System.out.println(URLEncoder.encode(text2.substring(5))  );
        String plainText2 = decrypt(text2.substring(5), PRIVATE_KEY2);
        log.info("解密后明文:{}", plainText2);   //{"timestamp":1685087193715,"userId":"test000001"}





        //最新 2023年6月9日09:15:03
        String ocomcode3 = "http%3A%2F%2Fhnjh.ocomtraffic.com%2Fm%2F%23mine%3Fcode%3D6JUu1TxGUwXnJvh6VrSohKN%2Bkt3bNM%2FnIOtD9uC%2BU5FNdiejNestR1GUjH2RgLfpnHTXPAx5qcPA1y0BqsfB7caYk8Gmne3cgPoWV%2F%2FIXXJMulT%2F65GGgxYXrgxSiPkViXW2Ou3bpez%2BDypdgH704q7QJa5rhre0oKoI%2F%2BtAWa29x%2FItjSkeZWzZMTC9gSNy5s%2FZ3sWN3znImJX95G6opSBiQsq0cIFRh7Bvgqo9Lg9NKpxl3CpaTjTN1KqetjWEhoyUYJpr8dRqe160NnItPHtakfKiG%2FWXhmrp4HGHdpI3SbpxQ3d57WZtfq1zC%2BmBMWHe9Xqpo1WcAPDH5oCkhgsKvMZH0lxJ8N2s9fMQ8TdYGSpBvuKbXpuSU9Ik%2FQHVfK0f2CZQwIDVX%2FT4Yi987ZaVYNr%2FxYEaEKPFBDgPg2wx%2FuqxcuvEhFb6PEZwotvKijLsC7fc0Y0UePg2JPqw0P4QemNadXox1E4KpX8wbS7QXz9qcxgtW9u4lRrGF%2BHkLYFZ2AJCPZMkPAyBjtupyRf9O7tzfQ4%2FOffjGHbjuAnJQGgEt%2FyreWoSTvt7ZkvJIy%2FZqI5LP0QfkAQNlkpwvWnNZ5EvDWya9MsmLGRE9i7yWMIiljJVbxmFqAm8IyvpIp4eMymL2UjSTSYRSkfYFOcrSyQmreAQBjPA1A%2Ba9mM%3D";
        String ocomcodeUrlDecode1 =   URLDecoder.decode(ocomcode3, "UTF-8");
        log.info("接收后处理url:{}", ocomcodeUrlDecode1);
        String text3 = ocomcodeUrlDecode1.split("\\?")[1];
        System.out.println(text3.substring(5));
        System.out.println(URLEncoder.encode(text3.substring(5))  );
        String plainText4 = decrypt(text3.substring(5), PRIVATE_KEY4);
        log.info("解密后明文:{}", plainText4);   //{"timestamp":1685087193715,"userId":"test000001"}


        String juy ="{\"timestamp\":1686213466425,\"userId\":\"77889944\"}";
        String  enen = encrypt(juy,PUBLIC_KEY4);

        System.out.println("http://hnjh.ocomtraffic.com/m/#mine?code="+URLEncoder.encode(enen, "UTF-8"));



        System.out.println("http://hnjh.ocomtraffic.com/m/#mine?code="+URLEncoder.encode("TWN+jIRkgc2ja72ZbOdU/V6ClhYbK0XVsYYfvs7TDJeHnurWWBlEDJAOD2OwSRTs2TsDKGDW7otgd1Fg8K8RszKyzAp9qYx9umpjIS8xxNNOHq8BftiHTtP+8tI0obLjvl5kxennvV1a5f0pR8+D87BMgHBD6w815PuzHZWfkAdLtc7mlSpLey6Qgv0fES45qblg85qb8PSzIKD1SSk8IkIRl4aNj/hCdKH9d12j6oeJ43wG8zZZssfj5kUut+fM+8utyuBxBu1gYwempO2Fe0Cy9cGG1fkSmYzt9FmuaacxPf2DmcQ+fcvYl4bHOT7Uutz/MjzpzTnpyC9n67E5qlGSKpYvI0fLjAswbVWXgXB5HmMIAWQPLFn2UnIVWO3/5+I6fDb9j6oIvQjWjAbqNZlHIf5ffxIz5hLqkNhJYYFbcuN/1qdktSNBMUewaSfZW7wFjZWgaDFMfCmal/T2DvwYnyN75KtFbuQvij6V5R7sqRigQgVrHUNewUfUbsQh8KU4Dui6AY4FhGbAU5SzbXWCQWjKd6WmWC1FyNYtGAE0WYPyb9MfXReXKO7Eo1UaTPJyb9qfaz0Vq21kjrGLNrMrnqDemjzd/3BFFE/tXQrZ5RVKgBNiERYbdfKuhvQFyMGGLJHhUj3JyEayB3eW4H3xWVvbsr0G8HBx3w=", "UTF-8"));

        log.info("解密7890");

        String content = "J-gkHjblMWRq-NXPmOgrAqgj6Pjxnmc9S8tDkXC3xtNEVvDT6ACddNN8MRutfh4VxFk3iDzMBYmJkqtgJA4eDDneUqjLmH2QPzzBVlyiagoCCu8dIaToJ8hz1Kp8x4omyj5mit-Ryqm8xlUC3VfzhYmXdPcf_D03hnm7imTvKfE";
        String decrypt = decrypt(content, zhxy_pri_key);
        System.out.println(decrypt);
    }
    static  String zhxy_pri_key = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAhQKrwgMA9qQP2bn6VB-bVUoQEGHmWAucuOMvbN5IXfg-XQvaGKhAVv_hIbZNYBOTZsS8aYtL8d45vM4HGBQSFQIDAQABAkANJLJsPXe-539ZeHMwFN94khT8SXBFiwA1lN1-2Ig2IMksgAd6ICLOKtuiXntAGNaNRYAWOJ23f8WIGdmTKQWRAiEAvj2dKiK8Oi8DjuQr41X9CmIrcyoBnDI6ypzS9xnLn2MCIQCy_MGLWWVs2Dnq8CKfOYVur69emxAXyduG2SqXTlkuJwIgJllPRD4qSWROyFAwlKwxzRULAzUVjAIIHe3NDSizBlcCICy_tp_hRNNWp_xN90n5tpt6vwyXFgnshL8NEnHru64nAiBFhMs4wUBcAM8scM9ZBSHZ0ldu_K3owPloa6g6aDq6vQ";
    static String zhxy_pub_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIUCq8IDAPakD9m5-lQfm1VKEBBh5lgLnLjjL2zeSF34Pl0L2hioQFb_4SG2TWATk2bEvGmLS_HeObzOBxgUEhUCAwEAAQ";

}



